<?php

namespace polymerize\user\module\user;

use app\common\InstanceTrait;
use app\common\LoginType;
use app\common\SmsType;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use support\Cache;
use support\Redis;

class ForgetPassword
{
    use InstanceTrait;

    /**
     * 手机验证码忘记密码修改密码[发送短信验证]
     *
     * @param int    $mobile
     * @param int    $smsCode
     * @param string $password
     * @return array
     */
    public function forgetPassword(int $mobile, int $smsCode, string $password): array
    {
        //判断手机号是否为当前登录用户的手机号
        $where[] = ['mobile', '=', $mobile];
        $userId  = UserModel::where($where)->value('id');
        if (!$userId) return ['code' => 400, 'msg' => '该手机号码未注册'];

        $expireTime = 2;
        $lockKey    = __METHOD__ . $mobile;
        $lock       = Redis::setNx($lockKey, 1);
        Redis::expire($lockKey, $expireTime);
        if (!$lock) return ['code' => 400, 'msg' => MANY_TIMES_REQUEST];
        $smsKey = 'SMS_CODE_' . md5($mobile . SmsType::SMS_CODE_CHANGE_PASSWORD->value);
        if ($smsCode != Cache::get($smsKey)) return ['code' => 400, 'msg' => '短信验证码错误'];
        Cache::delete($smsKey);
        if (Redis::ttl($lockKey) == -1) Redis::expire($lockKey, $expireTime);  //防止死锁

        //修改密码 md5(md5(12345).id)
        $data = ['password' => md5($password . $userId), 'u_time' => myDate()];
        $res1 = UserModel::updateDataCache($where, $data);

        $param = ['uid' => $userId, 'type' => 3, 'user_status' => 1, 'status' => 1, 'login_type' => LoginType::LOGIN_TYPE_PHONE->value];
        $res2  = UserBehaviorLog::log($param);

        return $res1 && $res2 ? ['code' => 200, 'msg' => ''] : ['code' => 400, 'msg' => '操作失败'];
    }
}
